﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;

namespace Lilium.Web.Mvc.AjaxControlToolkit
{
	public class AnimationExtenderControlBase: ToolkitExtenderBase
	{
		public AnimationExtenderControlBase(string scriptType, string elementID)
			: base(scriptType, elementID)
		{
		}

		/// <summary>
		/// This will prevent serializing the Animations property to the Xml-Script
		/// </summary>
		/// <returns>True when we have content in DesignMode, false otherwise</returns>
		[EditorBrowsable(EditorBrowsableState.Never)]
		public bool ShouldSerializeAnimations()
		{	// MVC экстендеры не являются компонентами и не могут находиться в дизайн-режиме.
			//if (DesignMode)
			//	return !string.IsNullOrEmpty(_animations);
			return false;
		}

		#region public string Animations

		private string m_Animations;

		[PersistenceMode(PersistenceMode.InnerProperty)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		//[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]
		[TypeConverter(typeof(MultilineStringConverter))]
		[ExtenderControlProperty()]
		public string Animations
		{
			[DebuggerNonUserCodeAttribute]
			get
			{
				return m_Animations ?? string.Empty;
			}
			[DebuggerNonUserCodeAttribute]
			set
			{
				if (value != null)
					value = TrimForDesigner(value);
				if (m_Animations != value)
				{
					m_Animations = value;
					Animation.Parse(m_Animations, this);
				}
			}
		}

		#endregion

		/// <summary>
		/// We have to trim the Animations string that we expose in the designer
		/// or else it will end up inserting a new blank line at the top of the
		/// string every time we make a change.  However, we only want to trim the
		/// blank lines off the top and leave any other leading whitespace on the
		/// line with the first content.  For an example of what happens if we
		/// don't do this, change the XmlDataSource.Data property in the designer.
		/// </summary>
		/// <param name="value">String to trim</param>
		/// <returns>Trimmed string</returns>
		private static string TrimForDesigner(string value)
		{
			if (string.IsNullOrEmpty(value))
				return value;

			// Get the index of the first non-whitespace character
			int i;
			for (i = 0; i < value.Length; i++)
				if (!Char.IsWhiteSpace(value[i]))
					break;

			// Remove any lines of just whitespace from the top
			i = value.LastIndexOf('\n', i);
			if (i >= 0)
				value = value.Substring(i + 1);

			// Trim anything else off the bottom
			return value.TrimEnd();
		}
	}
}
